﻿using AuthCenter.Token.Dto;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AuthCenter.Token
{
    public class GlobalToken
    {
        public static string Make(Guid onlineId, Guid userId, string password)
        {
            var token = string.Empty;

            token = JwtToken.Create(new Dictionary<string, string> { ["oid"] = onlineId.ToString(), ["uid"] = userId.ToString() }, password);
            return token;
        }

        public static TokenBag GetOnlineID(string token, string password)
        {
            var bag = new TokenBag();
            var json = JwtToken.ValidateJwtToken(token, password);
            if (!string.IsNullOrEmpty(json) && json[0] != 'e')
            {
                var obj = JsonConvert.DeserializeObject<IDictionary<string, string>>(json);
                if (obj != null)
                {
                    if (obj.ContainsKey("oid") && Guid.TryParse(obj["oid"], out Guid oid))
                    {
                        bag.OnlineID = oid;
                    }

                    if (obj.ContainsKey("uid") && Guid.TryParse(obj["uid"], out Guid uid))
                    {
                        bag.UserID = uid;
                    }

                }
            }

            return bag;
        }

        public static string ReadScheme(string token)
        {
            return token.Split(" ")[0];
        }
        public static string ReadToken(string token)
        {
            var bag = token.Split(' ');
            if (bag.Length > 1)
            {
                return bag[1];
            }
            return string.Empty;
        }
    }
}
